// pages/merchant/store-management/index.js
const apiService = require('../../../utils/api.js');

Page({
  data: {
    // 门店统计
    storeStats: {
      total: 0,
      active: 0,
      employees: 0,
      devices: 0
    },
    
    // 门店列表
    storeList: [],
    
    // 员工列表
    employeeList: [],
    
    // 加载状态
    isLoading: false,
    
    // 弹窗状态
    showAddStoreModal: false,
    showEmployeeModal: false,
    showAddEmployeeModal: false,
    
    // 选中的门店
    selectedStore: {},
    
    // 新门店信息
    newStore: {
      storeName: '',
      address: '',
      phone: '',
      businessHours: '',
      description: ''
    },
    
    // 新员工信息
    newEmployee: {
      name: '',
      phone: '',
      role: '员工',
      storeId: '',
      description: ''
    },
    
    // 角色选项
    roleOptions: ['店长', '员工', '收银员', '设备管理员'],
    roleIndex: 1,
    
    // 门店选择索引
    storeIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('门店管理页面加载', options);
    this.loadStoreList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadStoreList();
  },

  /**
   * 加载门店列表
   */
  async loadStoreList() {
    this.setData({ isLoading: true });
    
    try {
      // 模拟门店数据，实际项目中应该调用API
      const mockStores = [
        {
          storeId: 'store_001',
          storeName: '超级泡泡蓝光店',
          address: '北京市朝阳区蓝光大厦1层',
          phone: '010-12345678',
          businessHours: '09:00-21:00',
          description: '专业宠物洗浴美容服务',
          status: 'active',
          statusText: '营业中',
          statusClass: 'active',
          employeeCount: 5,
          deviceCount: 8,
          roomCount: 6
        },
        {
          storeId: 'store_002',
          storeName: '超级泡泡望京店',
          address: '北京市朝阳区望京SOHO T3',
          phone: '010-87654321',
          businessHours: '08:30-22:00',
          description: '24小时宠物寄养服务',
          status: 'active',
          statusText: '营业中',
          statusClass: 'active',
          employeeCount: 3,
          deviceCount: 5,
          roomCount: 4
        },
        {
          storeId: 'store_003',
          storeName: '超级泡泡三里屯店',
          address: '北京市朝阳区三里屯太古里',
          phone: '010-11223344',
          businessHours: '10:00-20:00',
          description: '高端宠物美容服务',
          status: 'maintenance',
          statusText: '维护中',
          statusClass: 'maintenance',
          employeeCount: 2,
          deviceCount: 3,
          roomCount: 2
        }
      ];

      // 计算统计数据
      const stats = {
        total: mockStores.length,
        active: mockStores.filter(s => s.status === 'active').length,
        employees: mockStores.reduce((sum, s) => sum + s.employeeCount, 0),
        devices: mockStores.reduce((sum, s) => sum + s.deviceCount, 0)
      };

      this.setData({
        storeList: mockStores,
        storeStats: stats
      });

      console.log('门店列表加载成功:', mockStores);
      
    } catch (error) {
      console.error('加载门店列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ isLoading: false });
    }
  },

  /**
   * 添加门店
   */
  onAddStore() {
    this.setData({ 
      showAddStoreModal: true,
      newStore: {
        storeName: '',
        address: '',
        phone: '',
        businessHours: '',
        description: ''
      }
    });
  },

  /**
   * 关闭添加门店弹窗
   */
  onCloseAddStoreModal() {
    this.setData({ showAddStoreModal: false });
  },

  /**
   * 门店名称输入
   */
  onStoreNameInput(e) {
    this.setData({
      'newStore.storeName': e.detail.value
    });
  },

  /**
   * 地址输入
   */
  onAddressInput(e) {
    this.setData({
      'newStore.address': e.detail.value
    });
  },

  /**
   * 电话输入
   */
  onPhoneInput(e) {
    this.setData({
      'newStore.phone': e.detail.value
    });
  },

  /**
   * 营业时间输入
   */
  onBusinessHoursInput(e) {
    this.setData({
      'newStore.businessHours': e.detail.value
    });
  },

  /**
   * 描述输入
   */
  onDescriptionInput(e) {
    this.setData({
      'newStore.description': e.detail.value
    });
  },

  /**
   * 确认添加门店
   */
  async onConfirmAddStore() {
    const { newStore } = this.data;
    
    // 验证输入
    if (!newStore.storeName.trim()) {
      wx.showToast({
        title: '请输入门店名称',
        icon: 'none'
      });
      return;
    }
    
    if (!newStore.address.trim()) {
      wx.showToast({
        title: '请输入门店地址',
        icon: 'none'
      });
      return;
    }
    
    if (!newStore.phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '添加中...' });
    
    try {
      // 模拟添加门店，实际项目中应该调用API
      const newStoreData = {
        storeId: 'store_' + Date.now(),
        storeName: newStore.storeName,
        address: newStore.address,
        phone: newStore.phone,
        businessHours: newStore.businessHours || '09:00-21:00',
        description: newStore.description,
        status: 'active',
        statusText: '营业中',
        statusClass: 'active',
        employeeCount: 0,
        deviceCount: 0,
        roomCount: 0
      };

      // 添加到门店列表
      const storeList = [...this.data.storeList, newStoreData];
      const stats = {
        total: storeList.length,
        active: storeList.filter(s => s.status === 'active').length,
        employees: storeList.reduce((sum, s) => sum + s.employeeCount, 0),
        devices: storeList.reduce((sum, s) => sum + s.deviceCount, 0)
      };

      this.setData({
        storeList,
        storeStats: stats,
        showAddStoreModal: false
      });

      wx.showToast({
        title: '添加成功',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('添加门店失败:', error);
      wx.showToast({
        title: '添加失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 门店点击
   */
  onStoreTap(e) {
    const store = e.currentTarget.dataset.store;
    console.log('点击门店:', store);
  },

  /**
   * 编辑门店
   */
  onEditStore(e) {
    const store = e.currentTarget.dataset.store;
    console.log('编辑门店:', store);
    
    wx.showToast({
      title: '编辑功能开发中',
      icon: 'none'
    });
  },

  /**
   * 管理员工
   */
  onManageEmployees(e) {
    const store = e.currentTarget.dataset.store;
    this.loadEmployeeList(store);
    this.setData({
      selectedStore: store,
      showEmployeeModal: true
    });
  },

  /**
   * 关闭员工管理弹窗
   */
  onCloseEmployeeModal() {
    this.setData({ showEmployeeModal: false });
  },

  /**
   * 加载员工列表
   */
  async loadEmployeeList(store) {
    try {
      // 模拟员工数据，实际项目中应该调用API
      const mockEmployees = [
        {
          employeeId: 'emp_001',
          name: '张店长',
          phone: '138****1111',
          role: '店长',
          storeId: store.storeId,
          status: 'active',
          statusText: '在职',
          statusClass: 'active',
          avatarUrl: '/images/default_avatar.png'
        },
        {
          employeeId: 'emp_002',
          name: '李员工',
          phone: '139****2222',
          role: '员工',
          storeId: store.storeId,
          status: 'active',
          statusText: '在职',
          statusClass: 'active',
          avatarUrl: '/images/default_avatar.png'
        },
        {
          employeeId: 'emp_003',
          name: '王收银',
          phone: '137****3333',
          role: '收银员',
          storeId: store.storeId,
          status: 'inactive',
          statusText: '离职',
          statusClass: 'inactive',
          avatarUrl: '/images/default_avatar.png'
        }
      ];

      this.setData({ employeeList: mockEmployees });
      
    } catch (error) {
      console.error('加载员工列表失败:', error);
    }
  },

  /**
   * 添加员工
   */
  onAddEmployee() {
    this.setData({ 
      showAddEmployeeModal: true,
      newEmployee: {
        name: '',
        phone: '',
        role: '员工',
        storeId: '',
        description: ''
      },
      roleIndex: 1,
      storeIndex: 0
    });
  },

  /**
   * 关闭添加员工弹窗
   */
  onCloseAddEmployeeModal() {
    this.setData({ showAddEmployeeModal: false });
  },

  /**
   * 员工姓名输入
   */
  onEmployeeNameInput(e) {
    this.setData({
      'newEmployee.name': e.detail.value
    });
  },

  /**
   * 员工电话输入
   */
  onEmployeePhoneInput(e) {
    this.setData({
      'newEmployee.phone': e.detail.value
    });
  },

  /**
   * 角色选择
   */
  onRoleChange(e) {
    this.setData({
      roleIndex: e.detail.value,
      'newEmployee.role': this.data.roleOptions[e.detail.value]
    });
  },

  /**
   * 门店选择
   */
  onStoreChange(e) {
    this.setData({
      storeIndex: e.detail.value,
      'newEmployee.storeId': this.data.storeList[e.detail.value].storeId
    });
  },

  /**
   * 员工描述输入
   */
  onEmployeeDescriptionInput(e) {
    this.setData({
      'newEmployee.description': e.detail.value
    });
  },

  /**
   * 确认添加员工
   */
  async onConfirmAddEmployee() {
    const { newEmployee, storeList, storeIndex } = this.data;
    
    // 验证输入
    if (!newEmployee.name.trim()) {
      wx.showToast({
        title: '请输入员工姓名',
        icon: 'none'
      });
      return;
    }
    
    if (!newEmployee.phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '添加中...' });
    
    try {
      // 模拟添加员工，实际项目中应该调用API
      const newEmployeeData = {
        employeeId: 'emp_' + Date.now(),
        name: newEmployee.name,
        phone: newEmployee.phone,
        role: newEmployee.role,
        storeId: storeList[storeIndex].storeId,
        status: 'active',
        statusText: '在职',
        statusClass: 'active',
        avatarUrl: '/images/default_avatar.png'
      };

      // 更新门店员工数量
      const storeList = this.data.storeList.map(store => {
        if (store.storeId === newEmployeeData.storeId) {
          return {
            ...store,
            employeeCount: store.employeeCount + 1
          };
        }
        return store;
      });

      // 更新统计数据
      const stats = {
        total: storeList.length,
        active: storeList.filter(s => s.status === 'active').length,
        employees: storeList.reduce((sum, s) => sum + s.employeeCount, 0),
        devices: storeList.reduce((sum, s) => sum + s.deviceCount, 0)
      };

      this.setData({
        storeList,
        storeStats: stats,
        showAddEmployeeModal: false
      });

      wx.showToast({
        title: '添加成功',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('添加员工失败:', error);
      wx.showToast({
        title: '添加失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 添加员工到门店
   */
  onAddEmployeeToStore() {
    this.setData({ 
      showAddEmployeeModal: true,
      showEmployeeModal: false,
      newEmployee: {
        name: '',
        phone: '',
        role: '员工',
        storeId: this.data.selectedStore.storeId,
        description: ''
      },
      roleIndex: 1,
      storeIndex: this.data.storeList.findIndex(s => s.storeId === this.data.selectedStore.storeId)
    });
  },

  /**
   * 编辑员工
   */
  onEditEmployee(e) {
    const employee = e.currentTarget.dataset.employee;
    console.log('编辑员工:', employee);
    
    wx.showToast({
      title: '编辑功能开发中',
      icon: 'none'
    });
  },

  /**
   * 删除员工
   */
  onDeleteEmployee(e) {
    const employee = e.currentTarget.dataset.employee;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除员工"${employee.name}"吗？`,
      success: (res) => {
        if (res.confirm) {
          this.deleteEmployee(employee);
        }
      }
    });
  },

  /**
   * 删除员工
   */
  async deleteEmployee(employee) {
    wx.showLoading({ title: '删除中...' });
    
    try {
      // 模拟删除员工，实际项目中应该调用API
      console.log('删除员工:', employee.name);
      
      // 从员工列表中移除
      const employeeList = this.data.employeeList.filter(emp => emp.employeeId !== employee.employeeId);
      
      // 更新门店员工数量
      const storeList = this.data.storeList.map(store => {
        if (store.storeId === employee.storeId) {
          return {
            ...store,
            employeeCount: Math.max(0, store.employeeCount - 1)
          };
        }
        return store;
      });

      // 更新统计数据
      const stats = {
        total: storeList.length,
        active: storeList.filter(s => s.status === 'active').length,
        employees: storeList.reduce((sum, s) => sum + s.employeeCount, 0),
        devices: storeList.reduce((sum, s) => sum + s.deviceCount, 0)
      };

      this.setData({
        employeeList,
        storeList,
        storeStats: stats
      });

      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('删除员工失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 删除门店
   */
  onDeleteStore(e) {
    const store = e.currentTarget.dataset.store;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除门店"${store.storeName}"吗？删除后将无法恢复。`,
      success: (res) => {
        if (res.confirm) {
          this.deleteStore(store);
        }
      }
    });
  },

  /**
   * 删除门店
   */
  async deleteStore(store) {
    wx.showLoading({ title: '删除中...' });
    
    try {
      // 模拟删除门店，实际项目中应该调用API
      console.log('删除门店:', store.storeName);
      
      // 从门店列表中移除
      const storeList = this.data.storeList.filter(s => s.storeId !== store.storeId);
      
      // 更新统计数据
      const stats = {
        total: storeList.length,
        active: storeList.filter(s => s.status === 'active').length,
        employees: storeList.reduce((sum, s) => sum + s.employeeCount, 0),
        devices: storeList.reduce((sum, s) => sum + s.deviceCount, 0)
      };

      this.setData({
        storeList,
        storeStats: stats
      });

      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('删除门店失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 防止弹窗滚动穿透
   */
  preventTouchMove() {
    return false;
  }
});